package com.gouqi.mall.controller;

import com.gouqi.mall.utils.CodeUtil;
import com.gouqi.mall.utils.URLUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 *  @author xiaofei
 *  @time:2020-4-3
 */
@CrossOrigin
@Api(basePath = "/api/v1", value = "验证码接口", description = "验证码")
@Component
@RestController
@RequestMapping(value = "/code")
public class CodeController extends BaseController{
    /**
     * 生成验证码
     * @return 4位字符+数字验证码
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/generateCode.do",method = RequestMethod.GET, produces = "application/json")
    @ApiOperation(value = "生成验证码",notes = "生成一个验证码图片")
    public String generateCode(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        JSONObject json = new JSONObject();
        //请求地址
        String url = URLUtils.getOrigin(request)+"/login/generateCode.do";
        json.put("codeUrl",url);
        try {
            response.setContentType("image/png");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Expire", "0");
            response.setHeader("Pragma", "no-cache");
            CodeUtil validateCode = new CodeUtil();
            // 直接返回图片
            String codeImage = validateCode.getRandomCodeImage(request, response);
            json.put("codeImage",codeImage);
        } catch (Exception e) {
            System.out.println(e);
        }
        return json.toString();
    }
}
